﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Quellenverwaltung.Meta
{
    public class WebClientEncoding
    {

        private long CurLength;

        // Webclient kann hier nicht verwendet werden, da ein Bug in der Auswertung
        // des Char Encodings vorliegt. 
        // Cp. http://bytes.com/topic/c-sharp/answers/653250-webclient-encoding
        public string DownloadPage(string url)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            byte[] buffer = new byte[8096];

            using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
            {

                using (Stream s = resp.GetResponseStream())
                {
                    buffer = ReadStream(s);
                }

                string pageEncoding = "";
                Encoding e = Encoding.UTF8;
                if (resp.ContentEncoding != "")
                    pageEncoding = resp.ContentEncoding;
                else if (resp.CharacterSet != "")
                    pageEncoding = resp.CharacterSet;
                else if (resp.ContentType != "")
                    pageEncoding = GetCharacterSet(resp.ContentType);

                if (pageEncoding == "")
                    pageEncoding = GetCharacterSet(buffer);

                if (pageEncoding != "")
                {
                    try
                    {
                        e = Encoding.GetEncoding(pageEncoding);
                    }
                    catch
                    {
                        //MessageBox.Show("Invalid encoding: " + pageEncoding);
                    }
                }

                string data = e.GetString(buffer);

                return data;
            }
        }

        private string GetCharacterSet(string s)
        {
            s = s.ToUpper();
            int start = s.LastIndexOf("CHARSET");
            if (start == -1)
                return "";

            start = s.IndexOf("=", start);
            if (start == -1)
                return "";

            start++;
            s = s.Substring(start).Trim();
            int end = s.Length;

            int i = s.IndexOf(";");
            if (i != -1)
                end = i;
            i = s.IndexOf("\"");
            if (i != -1 && i < end)
                end = i;
            i = s.IndexOf("'");
            if (i != -1 && i < end)
                end = i;
            i = s.IndexOf("/");
            if (i != -1 && i < end)
                end = i;

            return s.Substring(0, end).Trim();
        }

        private string GetCharacterSet(byte[] data)
        {
            string s = Encoding.Default.GetString(data);
            return GetCharacterSet(s);
        }

        private byte[] ReadStream(Stream s)
        {
            try
            {
                byte[] buffer = new byte[8096];
                using (MemoryStream ms = new MemoryStream())
                {
                    while (true)
                    {
                        int read = s.Read(buffer, 0, buffer.Length);
                        if (read <= 0)
                        {
                            CurLength = 0;
                            return ms.ToArray();
                        }
                        ms.Write(buffer, 0, read);
                        CurLength = ms.Length;
                    }
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
